﻿function scrollLoad(option) {
    if (window.isAjaxing) {
        return;
    }
    var total = resultHelper.total($(option.element).html());
    if (total > 0) {
        option.total = total;
    }
    if (option.data.PageSize * option.data.PageNo >= option.total && option.total != 0) return false;
    var scrollTop = $(this).scrollTop();
    var scrollHeight = $(document).height();
    var windowHeight = $(this).height();
    if (scrollTop + windowHeight < scrollHeight) {
        return false;
    }
    
    $(".loading").show();
    option.data.PageNo++;
    window.isAjaxing = true;
    $.ajax
    ({
        url: option.url,
        type: 'get',
        data: option.data,
        error: disposeError,
        success: function (result) {
            if (disposeException(result)) return;
            option.total = resultHelper.total(result);
            var html = resultHelper.html(result);
            $(option.element).append(html);
            $(".loading").hide();
        },
        complete: function () {
            window.isAjaxing = false;
        }
    });
}

/* result 帮助类
------------------------------*/
var resultHelper = function () { };

resultHelper.html = function (result) {

    var doc = "<div>" + result + "</div>";
    obj = $(doc);
    obj.find(".extra").remove();
    return obj.html();
};
resultHelper.total = function (result) {
    var total = $("<div>" + result + "</div>").find(".extra .total");
    if (total.length > 0) {
        return parseInt(total.html());
    }
    return 0;
};
function disposeError() {
    alert("网络忙，稍后再试！");
}

function disposeException(result) {
    if (result == null) return false;

    var error;
    try {
        error = result.Errors;

    } catch (e) {
    }

    if (error) {
        messageHelper.alert(error);
        return true;
    }

    var errors = $("<div>" + result + "</div>").find(".extra .errors");
    if (errors.length > 0) {
        messageHelper.alert(errors.html());
        return true;
    }

    return false;
}
